<?php

class Solicitud_SolicitudController extends Zend_Controller_Action {

    public function init() {
        /* Init ialize action controller here */
    }

    public function solicitudListFromAction() {
        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $auth = Zend_Auth::getInstance();
        $idUser = $auth->getIdentity()->id;
        $solicitudes = $solicitudDB->fetchAll('user_create=' . $idUser . ' and status!="ELIMINADO"');
        $this->view->solicitudes = $solicitudes;
    }

    public function solicitudListToAction() {
        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $auth = Zend_Auth::getInstance();
        $idUser = $auth->getIdentity()->id;

        $select = $solicitudDB->select()->setIntegrityCheck(false)
                ->from(array('s' => 'solicitud'), array('*'))
                ->join(array('su' => 'solicitud_user'), 's.id = su.solicitud_id and s.status!="ELIMINADO"');

        $solicitudes = $solicitudDB->fetchAll($select);
        $this->view->solicitudes = $solicitudes;
    }

    public function getUsers() {
        $userDB = new User_Model_DbTable_User();
        $users = $userDB->fetchAll('type="CLIENT" and client_departament=1 and estado=1');
        return $users;
    }

    public function solicitudAddAction() {
        $request = $this->getRequest();
        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $auth = Zend_Auth::getInstance();
        if ($request->isPost()) {
            $id_users = $request->getParam('to_users');

            $user_create = $auth->getIdentity()->id;
            $data = array(
                'subject' => $request->getParam('subject'),
                'detail' => $request->getParam('detail'),
                'user_create' => $user_create,
                'code_solicitud' => $request->getParam('code_solicitud'),
                'status' => 'PENDIENTE'
            );
            $index = $solicitudDB->insert($data);

            if ($index > 0) {
                $solicitudUserDB = new Solicitud_Model_DbTable_SolicitudUser();
                foreach ($id_users as $val) {
                    if ($val != null && $val != 0)
                        $solicitudUserDB->insert(array('user_id' => $val, 'solicitud_id' => $index));
                }
                /* email */
                $sendEmail = new Amz_Resource_SendEmailSolicitud();
                $sendEmail->sendEmail($index, $id_users, 'ADD_SOL');

                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Se ha enviado la solicitud.');
                $this->_helper->redirector->gotoUrlAndExit('/solicitud/solicitud/solicitud-add');
            }
        } else {
            $this->view->code = $this->createRandomCode();
            $this->view->users = $this->getUsers();
        }
    }

    public function solicitudEditAction() {
        $request = $this->getRequest();
        $idSol = $request->getParam('id');

        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $solicitudUserDB = new Solicitud_Model_DbTable_SolicitudUser();
        $solicitudAttachmentDB = new Solicitud_Model_DbTable_SolicitudAttachment();

        if ($request->isPost()) {
            $id_users = $request->getParam('to_users');

            $data = array(
                'subject' => $request->getParam('subject'),
                'detail' => $request->getParam('detail'),
                'status' => 'PENDIENTE'
            );
            $solicitudDB->update($data, 'id=' . $idSol);
            $solicitudUserDB->delete('solicitud_id=' . $idSol);
            foreach ($id_users as $val) {
                if ($val != null && $val != 0)
                    $solicitudUserDB->insert(array('user_id' => $val, 'solicitud_id' => $idSol));
            }
            /* email */
            $sendEmail = new Amz_Resource_SendEmailSolicitud();
            $sendEmail->sendEmail($idSol, $id_users, 'ADD_SOL');

            $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Se ha modificado y enviado la solicitud.');
            $this->_helper->redirector->gotoUrlAndExit('/solicitud/solicitud/solicitud-edit/id/' . $idSol);
        } else {
            $solicitud = $solicitudDB->fetchRow('id=' . $idSol);
            $this->view->solicitud = $solicitud;
            $this->view->users = $this->getUsers();
            $this->view->usersSolicitud = $solicitudUserDB->fetchAll('solicitud_id=' . $idSol);
            $this->view->attachments = $solicitudAttachmentDB->fetchAll('code="' . $solicitud->code_solicitud . '"');
        }
    }

    /**
     * Edita la solicitud por parte de los usuarios altos: ex Tatiana, Nadine...
     */
    public function solicitudEditToAction() {
        $request = $this->getRequest();
        $idSol = $request->getParam('id');

        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $solicitudUserDB = new Solicitud_Model_DbTable_SolicitudUser();
        $solicitudAttachmentDB = new Solicitud_Model_DbTable_SolicitudAttachment();

        $userDB = new User_Model_DbTable_User();

        if ($request->isPost()) {
            $id_user = $request->getParam('id_user');

            $data = array(
                'subject' => $request->getParam('subject'),
                'detail' => $request->getParam('detail'),
                'status' => 'PENDIENTE'
            );
            $solicitudDB->update($data, 'id=' . $idSol);

            /* email */
            $sendEmail = new Amz_Resource_SendEmailSolicitud();
            $sendEmail->sendEmail($idSol, array(0 => $id_user), 'ADD_SOL');

            $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Se ha modificado y enviado la solicitud.');
            $this->_helper->redirector->gotoUrlAndExit('/solicitud/solicitud/solicitud-edit-to/id/' . $idSol);
        } else {
            $solicitud = $solicitudDB->fetchRow('id=' . $idSol);
            $this->view->solicitud = $solicitud;
            $this->view->user = $userDB->fetchRow('id=' . $solicitud->user_create);
            $this->view->attachments = $solicitudAttachmentDB->fetchAll('code="' . $solicitud->code_solicitud . '"');
        }
    }

    public function solicitudViewFromAction() {
        $request = $this->getRequest();
        $id = $request->getParam('id');

        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $solicitudAttachmentDB = new Solicitud_Model_DbTable_SolicitudAttachment();

        $solicitudRow = $solicitudDB->fetchRow('id=' . $id);
        $this->view->solicitud = $solicitudRow;

        $attachments = $solicitudAttachmentDB->fetchAll('code="' . $solicitudRow->code_solicitud . '"');

        if ($attachments != null)
            $this->view->attachments = $attachments;
        else
            $this->view->attachments = null;
    }

    public function solicitudViewToAction() {
        $request = $this->getRequest();
        $id = $request->getParam('id');

        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $solicitudAttachmentDB = new Solicitud_Model_DbTable_SolicitudAttachment();

        $solicitudRow = $solicitudDB->fetchRow('id=' . $id);
        $this->view->solicitud = $solicitudRow;

        $attachments = $solicitudAttachmentDB->fetchAll('code="' . $solicitudRow->code_solicitud . '"');

        if ($attachments != null)
            $this->view->attachments = $attachments;
        else
            $this->view->attachments = null;
    }

    public function solicitudDeleteAction() {
        $request = $this->getRequest();
        $id = $request->getParam('id');

        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();
        $solicitudUsersDB = new Solicitud_Model_DbTable_SolicitudUser();

        $users = $solicitudUsersDB->fetchAll('solicitud_id=' . $id);
        if ($users != null)
            foreach ($users as $us) {
                $id_user[] = $us->user_id;
            }

        $solicitudRow = $solicitudDB->update(array('status' => 'ELIMINADO'), 'id=' . $id);
        /* email */
        $sendEmail = new Amz_Resource_SendEmailSolicitud();
        $sendEmail->sendEmail($id, $id_user, 'DEL_SOL');

        $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Se ha eliminado y notificado a los usuarios.');
        $this->_helper->redirector->gotoUrlAndExit('/solicitud/solicitud/solicitud-list-from/');
    }

    public function solicitudAprobadaAction() {
        $request = $this->getRequest();
        $id = $request->getParam('id');
        $solicitudDB = new Solicitud_Model_DbTable_Solicitud();

        $solicitudRow = $solicitudDB->fetchRow('id='.$id);
        $solicitudDB->update(array('status' => 'APROBADO'), 'id=' . $id);
        /* email */
        $sendEmail = new Amz_Resource_SendEmailSolicitud();
        $sendEmail->sendEmail($id, array(0=>$solicitudRow->user_create), 'APRO_SOL');

        $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Se ha aprobado y notificado al usuario.');
        $this->_helper->redirector->gotoUrlAndExit('/solicitud/solicitud/solicitud-view-to/');
    }

    private function createRandomCode() {
        $chars = "abcdefghijkmnopqrstuvwxyz023456789";
        srand((double) microtime() * 1000000);
        $i = 0;
        $pass = '';
        while ($i <= 4) {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        return $pass;
    }

}